import {
	IGridAbility,
	IMDViewControllerParams,
	IParam,
	IPickupGridViewAbility,
	IPickupGridViewController,
	IPickupGridViewStore,
	MDCtrlActionType,
	PickupGridViewActionType,
} from '@/core/interface';
import { MDViewController } from './md-view-controller';

/**
 * 选择表格视图控制器
 *
 * @export
 * @class PickupGridViewController
 * @extends {(GridViewController<T | PickupGridViewActionType, IPickupGridViewStore, IGridAbility>)}
 * @template T
 */
export class PickupGridViewController
	extends MDViewController<
		PickupGridViewActionType,
		IPickupGridViewStore,
		IPickupGridViewAbility
	>
	implements
		IPickupGridViewController<IPickupGridViewStore, IPickupGridViewAbility>
{
	/**
	 * 获取表格部件能力
	 *
	 * @protected
	 * @return {*}  {(IGridAbility | undefined)}
	 * @memberof GridViewController
	 */
	protected getMDCtrlAbility(): IGridAbility | undefined {
		const grid = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'GRID'
		);
		if (grid) {
			return this.getSubAbility<IGridAbility>(grid.name);
		}
		return undefined;
	}

	/**
	 * 处理视图初始化
	 *
	 * @protected
	 * @param {IMDViewControllerParams<PickupGridViewActionType, IPickupGridViewAbility>} params
	 * @memberof PickupGridViewController
	 */
	protected processViewInit(
		params: IMDViewControllerParams<
			PickupGridViewActionType,
			IPickupGridViewAbility
		>
	): void {
		super.processViewInit(params);
		Object.assign(this.store, { expandSearchForm: true });
	}

	/**
	 * 处理多数据部件行为
	 *
	 * @protected
	 * @template T
	 * @param {(T | MDCtrlActionType)} action
	 * @param {IParam[]} data
	 * @memberof PickupGridViewController
	 */
	protected handleMDCtrlAction<T>(
		action: T | MDCtrlActionType,
		data: IParam[]
	) {
		super.handleMDCtrlAction(action, data);
		switch (action) {
			case 'load':
				this.emit('viewDataLoaded', data);
				break;
		}
	}

	/**
	 * 处理数据部件数据激活
	 *
	 * @protected
	 * @param {IParam[]} data
	 * @memberof PickupGridViewController
	 */
	protected handleDataActive(data: IParam[]): void {
		this.emit('viewDataActive', data);
	}

	/**
	 * 选择全部
	 *
	 * @memberof PickupGridViewController
	 */
	public selectAll() {
		const grid = this.getMDCtrlAbility();
		if (grid) {
			grid.selectAll();
		}
	}

	/**
	 * 选中数据
	 *
	 * @param {IParam[]} items 需要选中的数据
	 * @param {boolean} [reverse] 是否反选
	 * @memberof PickupGridViewController
	 */
	public selectItems(items: IParam[], reverse?: boolean) {
		const grid = this.getMDCtrlAbility();
		if (grid) {
			grid.selectItems(items, reverse);
		}
	}

	/**
	 * 获取能力
	 *
	 * @return {*}  {IPickupGridViewAbility}
	 * @memberof PickupGridViewController
	 */
	public getAbility(): IPickupGridViewAbility {
		return {
			...super.getAbility(),
			selectAll: this.selectAll.bind(this),
			selectItems: this.selectItems.bind(this),
		};
	}
}
